package ebj.common.hadoop;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;

public class KerberosMultiUserTest {
	public static void main(String[] args) throws IOException {

		System.out.println(Runtime.getRuntime().availableProcessors());
		
		File logFile = new File("/tmp/adhoc-platform.log");

//		String[] cmds = new String[] { "ls", "-la" };
//		String[] cmds = new String[] {"/bin/bash", "-c", "echo $KRB5CCNAME; "
//				+ "/usr/local/bin/kinit -kt /home/biflt/keytab.files/adhoc/adhoc.keytab adhoc; "
//				+ "/usr/local/bin/klist; "
//				+ "hadoop fs -ls /user/adhoc"};
		String[] cmds = new String[] {"/bin/bash", "-c", "echo $KRB5CCNAME; "
				+ "/usr/local/bin/kinit -kt /home/biflt/biflt.keytab biflt; "
				+ "/usr/local/bin/klist; "
				+ "hive -e \"select * from dw_fltdb.es_demo_tbl;\""};

		ProcessBuilder processBuilder = new ProcessBuilder(cmds).directory(new File("/home/biflt/app"));
		processBuilder.redirectErrorStream(true)
			.redirectOutput(Redirect.appendTo(logFile));
		Map<String, String> env = processBuilder.environment();
		
		env.put("KRB5CCNAME", "/tmp/krb5cc_xxxxx");
		
		for (Entry<String, String> entry : env.entrySet()) {
			System.out.println(entry.getKey() + " = " + entry.getValue());
		}
		System.out.println("/////////////////////////////");
		try {
			Process process = processBuilder.start();
			// 5. 处理输出
			final InputStream inputStream = process.getInputStream();
			final InputStream errorStream = process.getErrorStream();

			CountDownLatch latch = new CountDownLatch(2);
			System.out.println("read contents from inputStream>>>>");			
			readFromIS(inputStream);
			System.out.println("read contents from errorStream>>>>");
			readFromIS(errorStream);
			
			latch.await();

			// 6. 获取结果，返回
			int rc = process.waitFor();
			System.out.println("rc <<<=>>> " + rc);
			int exit_val = process.exitValue();
			System.out.println("exit_val = " + exit_val);
			if (exit_val != 0) {  
			    throw new IOException("failed to execute:" + processBuilder.command() + " with result:" + exit_val);  
			} else {  
				System.exit(0); 
			}  
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private static void readFromIS(final InputStream inputStream)
			throws IOException {
		// 用一个读输出流类去读
		InputStreamReader isr = new InputStreamReader(inputStream);
		// 用缓冲器读行
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		// 直到读完为止
		while ((line = br.readLine()) != null) {
			System.out.println(">>>" + line);
		}
	}
}
